<template>
  <div class="accessList">
    <div class="top">
      <div class="icon fl">
        <img src="@/assets/img/bcp.png" width="20" height="20" style="margin: auto"/>
      </div>
      <div class="fl">
        <h5 class="title" style="margin-top: 8px">百度营销接入</h5>
        <p>请先在百度营销后台，客服账号授权选择“七陌联络云”授权，然后点击“获取授权列表” <span class="oprate-span" @click="openImgInfo">示例</span></p>
      </div>
      <a href="https://tuiguang.baidu.com" target="_blank">
        <el-button type="primary fr add" size="mini">授权</el-button>
      </a>
    </div>
    <div style="height: calc(100% - 102px)">
    <configTable
        ref="table"
        :headers="tableHeader"
        :data="tableData"
        :pagingData="tablePages"
        @pageChange="currentChangeFun"
        @pageSizeChange="sizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.prop !== 'oprate'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="item.width + 'px'"
              :resizable="false"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :width="120"
              fixed="right"
            >
              <template slot-scope="scope">
                 <span
                  class="oprate-span"
                  @click="editFun(scope.row)"
                >编辑</span>
                <span
                  class="oprate-span"
                  @click="enableFun(scope.row)"
                  v-if="!scope.row.flag"
                >启用</span>
                <el-tooltip class="item" effect="dark" content="停用后用户消息将无法接入系统，请慎重选择！" placement="top" v-else>
                  <span
                    class="oprate-span red-span"
                    @click="enableFun(scope.row)"
                  >停用</span>
                </el-tooltip>
                <!-- <span
                  class="oprate-span red-span"
                  @click="deleteFun(scope.row)"
                >删除</span> -->
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      </div>
    <drawer
      direction="rtl"
      class="wechatDrawer"
      :title="drawer.title"
      :drawer="drawer.isShow"
      @save="confirmFun"
      @cancelFun="cancelFun"
      @closeDraw="cancelFun">
      <template slot="column">
        <funTab
          :tabs="tabs"
          @input="setFunTabName"
          :value="'baseConfig'">
        </funTab>
        <accessAddOrEdit ref="wechatAccessInfo"></accessAddOrEdit>
      </template>
    </drawer>
    <img-info ref="imgInfo" :imgList="imgList"></img-info>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import configTable from '@/components/configCommon/table.vue'
import drawer from '@/common/views/drawer/index.vue'
import funTab from '@/components/cardLayout/FunTab.vue'
import accessAddOrEdit from './accessAddOrEdit.vue'
import { CommonModule } from '@/store/modules/common'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { commonAction, deepClone, isHasFuncOrMenus } from '@/utils/common'
import { ElForm } from 'element-ui/types/form'
import ImgInfo from './ImgInfo.vue'
interface PageObj {
  current: number
  pageSize: number
  total: number
}
interface DrawerObj {
  title: string
  isShow: boolean,
  childTabActiveName: string
}
@Component({
  name: 'wechatAccessList',
  components: { configTable, drawer, accessAddOrEdit, funTab, ImgInfo }
})
export default class WechatAccessList extends Vue {
  @Ref() private readonly wechatAccessInfo !: accessAddOrEdit
  @Ref() private readonly imgInfo!: ImgInfo
  [x: string]: any

  private checkHeaders: [] = []
  private tableHeader: any = [ // 列表表头
    { label: '百度营销企业名称', prop: 'name' },
    { label: '百度营销ucid', prop: 'ucid' },
    { label: '会话流程', prop: 'processName' },
    { label: '绑定时间', prop: 'createTime', sortable: true },
    { label: '最后修改时间', prop: 'updateTime', sortable: true, width: 145 }
  ]

  private beforeMount () {
    let width = 0
    console.log(this.$store.state.common.session.user)
    if (isHasFuncOrMenus('bcp_access_edit', this.$store.state.common.session.user, false)) {
      width += 40
    }
    if (isHasFuncOrMenus('bcp_access_enable', this.$store.state.common.session.user, false)) {
      width += 40
    }
    // if (isHasFuncOrMenus('bcp_access_delete', this.$store.state.common.session.user, false)) {
    //   width += 40
    // }
    if (width > 0) {
      this.tableHeader.push({ label: '操作', prop: 'oprate', width })
    }
  }

  private tablePages: PageObj = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private drawer: DrawerObj = {
    title: '修改会话流程',
    isShow: false,
    childTabActiveName: 'baseConfig'
  }

  private tabs: any = [
    { label: '基本配置', name: 'baseConfig' }
  ]

  private imgList = [
    require('@/assets/img/bcp1.png')
  ]

  private openImgInfo () {
    this.imgInfo.openImgInfo()
  }

  private tableData: any = [] // 列表数据

  private setFunTabName (name: string) { // 子菜单tab事件
    this.drawer.childTabActiveName = name
  }

  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private sizeChange (size: number) { // 改变页数
    this.tablePages.pageSize = size
    this.queryList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.tablePages.current = page
    this.queryList()
  }

  private queryList () { // 查询列表
    const actionData = {
      url: '/im-third-party/bcp/action/channelConfig/list',
      method: 'POST',
      data: { limit: this.tablePages.pageSize, page: this.tablePages.current }
    }
    channelConfigMoudle.channelCommonAction(actionData).then((res: any) => {
      if (res && res.success) {
        const list = res.data.list || []
        if (list.length > 0) {
          list.forEach((item: any) => {
            const processObj = CommonModule.publicCache.processListObj[item.processId]
            item.processName = processObj ? processObj.name : '--'
          })
        }
        this.tableData = res.data.list
        this.tablePages.total = res.data.count || 0
      }
    })
  }

  private editFun (row: any) {
    this.drawer.isShow = true
    this.drawer.title = '修改会话流程'
    this.$nextTick(() => {
      this.wechatAccessInfo.setAccessData(row)
    })
  }

  private async enableFun (row: any) {
    const str = row.flag ? '停用' : '启用'
    this.$confirm(`确定要${str}【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const actionData = {
        flag: !row.flag,
        name: row.name,
        processId: row.processId
      }
      const params = { url: `/im-third-party/bcp/action/channelConfig/update/${row._id}`, method: 'POST', data: actionData }
      const data: any = await commonAction(params)
      if (data.success) {
        this.$message.success(`${str}成功`)
        this.$updateCache('channelList', actionData, '_id', true)
        this.queryList()
      }
    })
  }

  private deleteFun (row: any) {
    if (row.flag) {
      this.$message.error('请先停用该渠道再删除')
      return
    }
    this.$confirm(`确定要删除【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const params = { url: `/im-third-party/bcp/action/channelConfig/delete/${row._id}`, method: 'GET' }
      const data: any = await commonAction(params)
      if (data.success) {
        this.$message.success('删除成功')
        this.$deleteCache('channelList', '_id', row._id, true)
        this.queryList()
      }
    })
  }

  private cancelFun () { // 取消
    this.drawer.isShow = false
  }

  private confirmFun () { // 保存
    const formRef = this.wechatAccessInfo.$refs.accessForm as ElForm
    formRef.validate(valide => {
      if (valide) {
        const sendData = deepClone(this.wechatAccessInfo.accessForm)
        const Id = sendData._id
        delete sendData._id
        const actionData = { url: `/im-third-party/bcp/action/channelConfig/update/${Id}`, method: 'POST', data: sendData }
        channelConfigMoudle.channelCommonAction(actionData).then(res => {
          if (res && res.success) {
            this.$message.success('操作成功')
            this.drawer.isShow = false
            this.queryList()
            this.$updateCache('channelList', sendData, '_id', true)
          }
        })
      }
    })
  }

  private mounted () {
    this.$getCache('/im-center/action/config/processConfig/processCache', ['processList'], true).then((res: any) => {
      if (res) {
        this.queryList()
      }
    })
  }

  private activated () {
    this.queryList()
  }
}
</script>
<style lang="stylus" scoped>
  .wechatDrawer
    >>> .drawer-contain
      height auto
      padding 6px 20px
  .accessList
    border 1px solid $border-main
    padding 16px
    border-radius 10px
    height 100%
    overflow auto
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
    box-sizing border-box
    margin 0 2px 2px 0
    height calc(100% - 40px)
    .top
      height 102px
      background-color #F4F9FD
      border-radius 4px
      width 100%
      padding 20px
      .icon
        width 40px
        height 40px
        line-height 40px
        text-align center
        margin 10px 19px 0px 0px
        background-color #fff
        border-radius 50%
        display flex
      .title
        color $fc-gray2
        margin-bottom 5px
      .add
        margin-top 15px
      p
       color #686E84
    .instiutionTableBox
      height calc(100% - 102px)
</style>
<style lang="stylus">
  .ecodeDialog
    height 75%
    .el-dialog__body
      height 75%
  .oprate-span
    cursor pointer
    color $c-main
    margin 0 4px
  .red-span,.disable-span
    color $c-danger
  .enable-span
    color $c-green
  .disable-span,.enable-span
    font-size 12px
</style>
